var app = angular.module('BaseServer');

//我们把socket服务定义成了一个factory，这样它只会被实例化一次，而且在整个应用的作用域范围内就成为了一个单例
app.factory('PublicSocket', function() {
	var socket = io.connect('http://' + document.location.hostname + ':8080');

	return {
		//监听接收消息
		on: function(eventName, callback){
			if(socket) {
				socket.on(eventName, function(data){
					callback(data);
				});
			}
		},
		//发送消息
		emit: function(eventName, data) {
			if (socket) {
				socket.emit(eventName, data);
			}
		},
		//发给自己
		toSelf: function(eventName, sendData) {
	      if (socket) {
	      	var data = {
	      		EventName: eventName,
	      		Data: sendData
	      	};
	        this.emit("toSelf", data);
	      }
    	},
    	//发给除自己的所有人
    	toOther: function(eventName, sendData) {
	      if (socket) {
	      	var data = {
	      		EventName: eventName,
	      		Data: sendData
	      	};
	        this.emit("toOther", data);
	      }
    	},
    	//发给所有人，包括自己
    	toAll: function(eventName, sendData) {
	      if (socket) {
	      	var data = {
	      		EventName: eventName,
	      		Data: sendData
	      	};
	        this.emit("toAll", data);
	      }
    	},
    	//加入房间
    	joinRoom: function(roomName) {
	      if (socket) {
	      	var data = {
	      		RoomName: roomName
	      	};
	        this.emit("joinRoom", data);
	      }
    	},
    	//离开房间
    	leaveRoom: function(roomName) {
	      if (socket) {
	      	var data = {
	      		RoomName: roomName
	      	};
	        this.emit("leaveRoom", data);
	      }
    	},
    	//向指定房间发送消息，不包括自己
    	toRoom: function(roomName, eventName, sendData) {
	      if (socket) {
	      	var data = {
	      		RoomName: roomName,
	      		EventName: eventName,
	      		Data: sendData
	      	};
	        this.emit("toRoom", data);
	      }
    	},
    	//向指定房间发送消息，包括自己
    	inRoom: function(roomName, eventName, sendData) {
	      if (socket) {
	      	var data = {
	      		RoomName: roomName,
	      		EventName: eventName,
	      		Data: sendData
	      	};
	        this.emit("inRoom", data);
	      }
    	}
	};
});